package com.acme.bankapp.domain.bank.transport;

import com.acme.bankapp.domain.bank.exception.ConnectionException;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class NetworkConnection implements Connection {

    private Socket socket;
    private DataOutputStream out;
    private DataInputStream in;

    public NetworkConnection(Socket socket) {
        if (socket == null)
            throw new IllegalArgumentException("Socket is null");
        this.socket = socket;

        try {
            this.out = new DataOutputStream(this.socket.getOutputStream());
            this.in = new DataInputStream(this.socket.getInputStream());
        } catch (IOException e) {
            throw new IllegalArgumentException("Bad socket", e);
        }
    }

    @Override
    public String readLine() throws ConnectionException {
        try {
            return in.readUTF();
        } catch (IOException e) {
            throw new ConnectionException(e);
        }
    }

    @Override
    public void writeLine(String line) throws ConnectionException {
        try {
            if (line == null)
                line = "";
            out.writeUTF(line);
            out.flush();
        } catch (IOException e) {
            throw new ConnectionException(e);
        }
    }

    @Override
    public void close() throws ConnectionException {
        try {
            out.flush();
            if (!socket.isClosed())
                socket.close();
        } catch (IOException e) {
            try {
                if (!socket.isClosed())
                    socket.close();
            } catch (IOException ioe) {
                throw new ConnectionException(ioe);
            }
        }
    }
}
